package com.apes.crm.vip.base;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * 功能：会员活跃度 Service
 *
 * @author HuJianlin
 * @create 2018-03-15 14:35
 */
@Service("vipLivenessService")
public class VipLivenessService extends DomainService {

    @Autowired
    VipLivenessRepository vipLivenessRepository;

    public VipLiveness save(SimpleRequest request) {
        VipLiveness vipLiveness = request.getO(VipLiveness.class);
        vipLivenessRepository.saveAndFlush(vipLiveness);
        return vipLiveness;
    }

    public VipLiveness update(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        VipLiveness oldVipLiveness = vipLivenessRepository.findOne(id);
        if (oldVipLiveness == null) throw new RuntimeException("会员活跃度【" + id + "】在系统中不存在。");
        if (oldVipLiveness.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");

        VipLiveness vipLiveness = request.getO(VipLiveness.class);
        return vipLivenessRepository.saveAndFlush(vipLiveness);
    }

    public Page<VipLiveness> find(SimpleRequest request) {
        return vipLivenessRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")));
    }

}
